package com.ruoyi.business.controller;

import com.ruoyi.business.service.IWsdSchoolsService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.SchoolTree.Grade;
import com.ruoyi.common.core.domain.SchoolTree.School;
import com.ruoyi.common.core.domain.SchoolTree.Class;
import com.ruoyi.common.core.domain.SchoolTree.SchoolGradeClassVO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WsdSchools;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 学校信息Controller
 *
 * @author ruoyi
 * @date 2024-04-14
 */
@RestController
@RequestMapping("wsd_schools")
public class WsdSchoolsController extends BaseController {

    @Autowired
    private IWsdSchoolsService wsdSchoolsService;


    /**
     * 查询学校信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:schools:list')")
    @GetMapping("/list")
    public TableDataInfo list(WsdSchools wsdSchools)
    {
        //获取当前登陆用户的schoolId
        SysUser user = getLoginUser().getUser();
        wsdSchools.setId("admin".equals(user.getUserName()) ? null : user.getSchoolId());
        startPage();
        List<WsdSchools> list = wsdSchoolsService.selectWsdSchoolsList(wsdSchools);
        return getDataTable(list);
    }

    @GetMapping("/schoolList")
    public List<WsdSchools> schoolList(WsdSchools wsdSchools)
    {
        //获取当前登陆用户的schoolId
        SysUser user = getLoginUser().getUser();
        wsdSchools.setId("admin".equals(user.getUserName()) ? null : user.getSchoolId());
        List<WsdSchools> list = wsdSchoolsService.selectWsdSchoolsList(wsdSchools);
        list.removeIf(school -> school.getId() == 1L);
        return list;
    }

    /**
     * 导出学校信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:schools:export')")
    @Log(title = "学校信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WsdSchools wsdSchools) {
        List<WsdSchools> list = wsdSchoolsService.selectWsdSchoolsList(wsdSchools);
        ExcelUtil<WsdSchools> util = new ExcelUtil<WsdSchools>(WsdSchools.class);
        util.exportExcel(response, list, "学校信息数据");
    }

    /**
     * 获取学校信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('business:schools:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(wsdSchoolsService.selectWsdSchoolsById(id));
    }

    /**
     * 新增学校信息
     */
    @PreAuthorize("@ss.hasPermi('business:schools:add')")
    @Log(title = "学校信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WsdSchools wsdSchools) {
        wsdSchools.setCreateTime(DateUtils.getNowDate());
        return toAjax(wsdSchoolsService.insertWsdSchools(wsdSchools));
    }

    /**
     * 修改学校信息
     */
    @PreAuthorize("@ss.hasPermi('business:schools:edit')")
    @Log(title = "学校信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WsdSchools wsdSchools)
    {
        return toAjax(wsdSchoolsService.updateWsdSchools(wsdSchools));
    }

    /**
     * 删除学校信息
     */
    @PreAuthorize("@ss.hasPermi('business:schools:remove')")
    @Log(title = "学校信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(wsdSchoolsService.deleteWsdSchoolsByIds(ids));
    }


    /**
     * 构建学校树状图
     * @return
     */
    @GetMapping("getSchoolTree/{roleId}")
    public AjaxResult getSchoolTree(@PathVariable Long roleId) {

         SysUser user = getLoginUser().getUser();
         Long schoolId = user.getSchoolId();
        // Long schoolId = 17L;

        // 先获取学校的所有年级和班级
        List<SchoolGradeClassVO> allSchoolData = wsdSchoolsService.getSchoolTree(schoolId);

        // 再获取与角色相关的年级和班级
        List<SchoolGradeClassVO> roleSpecificData = wsdSchoolsService.selectClassesByRoleId(roleId, schoolId);

        // 使用Set为基于角色的数据创建快速查找集合
        Set<Long> roleSpecificClassIds = roleSpecificData.stream()
                .map(SchoolGradeClassVO::getClassId)
                .collect(Collectors.toSet());

        // 过滤并标记角色相关数据
        Map<Long, School> schoolMap = new HashMap<>();
        for (SchoolGradeClassVO detail : allSchoolData) {
            School school = schoolMap.computeIfAbsent(detail.getSchoolId(), id -> new School(id, detail.getSchoolName()));
            Grade grade = school.getChildren().stream()
                    .filter(g -> g.getId().equals(detail.getGradeId()))
                    .findFirst()
                    .orElseGet(() -> {
                        Grade newGrade = new Grade(detail.getGradeId(), detail.getGradeName());
                        school.getChildren().add(newGrade);
                        return newGrade;
                    });

            Class newClass = new Class(detail.getClassId(), detail.getClassName());
            newClass.setSelected(roleSpecificClassIds.contains(detail.getClassId()));  // 标记为角色特定
            grade.getChildren().add(newClass);
        }

        List<School> schoolList = new ArrayList<>(schoolMap.values());
        return AjaxResult.success(schoolList);
    }

}
